package cn.chench.aspect;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import cn.chench.annotation.OAuth2Token;
import cn.chench.base.BaseResult;
import cn.chench.constant.ConstantUtil;
import cn.chench.constant.OAuth2Constant;
import cn.chench.model.OAuthUser;
import cn.chench.util.GsonUtil;
import cn.chench.util.LoggerUtil;
import cn.chench.util.NullUtil;
import cn.chench.util.RequestUtil;

/**
 * oauth2验证
 * @author chencaihui
 * @datetime 2020年10月15日 上午11:00:55
 */
@Component
@Aspect
public class OAuth2TokenAspect {
	
	//around->before->around->after->afterReturning
	//@Pointcut("@annotation(cn.chench.core.annotation.system.AutoAttachment)")
	//@Pointcut("execution(public * cn.chench.controller..*.*(..))")
	@Pointcut("@annotation(cn.chench.annotation.OAuth2Token)")
	public void checkOAuth2Token() {}
	
	@Around("checkOAuth2Token()")
    public Object onAround(ProceedingJoinPoint point) throws Throwable {
		org.aspectj.lang.Signature signature = point.getSignature();
	    MethodSignature methodSignature = (MethodSignature)signature;    
	    Method targetMethod = methodSignature.getMethod();
	    OAuth2Token oAuth2Token = targetMethod.getAnnotation(OAuth2Token.class);
	    if(oAuth2Token!=null){//需要授权
	    	try {
        		//String token = RequestUtil.getRequest().getHeader(OAuth2Constant.HEADER_AUTHORIZATION);
        		//LoggerUtil.info(token);
        		HttpServletRequest request = RequestUtil.getRequest();
    			String userStr = request.getHeader(OAuth2Constant.HEADER_OAUTH_USER);
    			if(NullUtil.isNull(userStr)){
    				return BaseResult.fail("您没有登录，请先登录");
    			}
    			OAuthUser oAuthUser = GsonUtil.json2Object(userStr, OAuthUser.class);
    			if(oAuthUser==null||oAuthUser.getId()==null||oAuthUser.getName()==null){
    				return BaseResult.fail("您没有登录，请先登录");
    			}
    			request.getSession().setAttribute(ConstantUtil.SESSION_USER, oAuthUser);
	        } catch(Throwable e){
	        	LoggerUtil.error("执行方法--->"+point.getSignature().getName()+"异常", e);
	        	return BaseResult.fail(e.getMessage());
	        }
	    }
    	return point.proceed(point.getArgs());
    }
	
}
